package com.haoze.nurse.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.service.AbstractService;
import com.haoze.common.utils.*;
import com.haoze.nurse.dao.NurseCatalogMapper;
import com.haoze.nurse.dao.NurseFormMapper;
import com.haoze.nurse.dto.NurseFormDTO;
import com.haoze.nurse.enumeration.NurseEnum;
import com.haoze.nurse.model.NurseCatalogEntity;
import com.haoze.nurse.model.NurseFormEntity;
import com.haoze.nurse.service.NurseCatalogService;
import com.haoze.nurse.service.NurseFormService;
import com.haoze.repository.model.ListTreeEntity;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Chenchao
 * @CreateTime: 2019-11-13 09:05
 */
@Service
public class NurseCatalogServiceImpl extends AbstractService<NurseCatalogEntity> implements NurseCatalogService {

    private static Logger logger = LoggerFactory.getLogger(NurseCatalogServiceImpl.class);

    @Resource
    private NurseCatalogMapper nurseCatalogMapper;

    @Resource
    private NurseFormMapper nurseFormMapper;

    @Resource
    private NurseFormService nurseFormService;

    @Override
    public Result list() {
        List<NurseCatalogEntity> list = nurseCatalogMapper.getCatalogList();
        List<NurseTree<NurseCatalogEntity>> trees = new ArrayList();
        for (NurseCatalogEntity entity : list) {
            NurseTree<NurseCatalogEntity> tree = new NurseTree();
            tree.setId(entity.getCtlId());
            tree.setParentId(entity.getParentCtlId());
            tree.setText(entity.getCtlName());
            trees.add(tree);
        }
        List<NurseTree<NurseCatalogEntity>> t = buildTree(trees);
        return ResultGenerator.genOkResult(t);
    }

    private <T> List<NurseTree<T>> buildTree(List<NurseTree<T>> nodes) {
        if (nodes == null) {
            return null;
        }
        List<NurseTree<T>> topNodes = new ArrayList<>();
        for (NurseTree<T> children : nodes) {
            String pid = children.getParentId();
            if (pid == null || "0".equals(pid)) {
                topNodes.add(children);
                continue;
            }
            for (NurseTree<T> parent : nodes) {
                String id = parent.getId();
                if (id != null && id.equals(pid)) {
                    parent.getChildren().add(children);
                    break;
                }
            }
        }
        return topNodes;
    }

    @Override
    public Result formList(String id) {
        List<Map<String, String>> list = nurseCatalogMapper.formList(id);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result getDetail(String id, String type) {
        NurseFormDTO dto = new NurseFormDTO();
        if (NurseEnum.NURSE_TYPE_ONE.getIndex().equals(type)) {
            NurseCatalogEntity catalogEntity = this.findById(id);
            dto.setId(catalogEntity.getCtlId());
            dto.setDeptId(catalogEntity.getDeptId());
            dto.setCtlId(catalogEntity.getParentCtlId());
            dto.setRoleType(catalogEntity.getRoleType());
            dto.setApplicableObject(catalogEntity.getApplicableObject());
            dto.setType(type);
            dto.setCtlName(catalogEntity.getCtlName());
        } else {
            NurseFormEntity nurseFormEntity = nurseFormService.findById(id);
            dto.setId(nurseFormEntity.getFormId());
            dto.setDeptId(nurseFormEntity.getDeptId());
            dto.setCtlId(nurseFormEntity.getCtlId());
            dto.setRoleType(nurseFormEntity.getRoleType());
            dto.setApplicableObject(nurseFormEntity.getApplicableObject());
            dto.setType(type);
        }
        return ResultGenerator.genOkResult(dto);
    }

    @Override
    public Result editDetail(NurseFormDTO dto) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        if (NurseEnum.NURSE_TYPE_ONE.getIndex().equals(dto.getType())) {
            NurseCatalogEntity catalogEntity = this.findById(dto.getId());
            catalogEntity.initUpdate();
            catalogEntity.setDeptId(dto.getDeptId());
            catalogEntity.setParentCtlId(dto.getCtlId());
            catalogEntity.setRoleType(dto.getRoleType());
            catalogEntity.setModifyUserId(userId);
            catalogEntity.setApplicableObject(dto.getApplicableObject());
            catalogEntity.setCtlName(dto.getCtlName());
            try {
                catalogEntity.setPyCode(ChineseCharactersCode.getPinyinCode(dto.getCtlName()).toUpperCase());
                catalogEntity.setWbCode(ChineseCharactersCode.getWBCode(dto.getCtlName()).toUpperCase());
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                logger.error("转拼音出错，字符异常。");
            }
            this.update(catalogEntity);
        } else {
            NurseFormEntity nurseFormEntity = nurseFormService.findById(dto.getId());
            nurseFormEntity.initUpdate();
            nurseFormEntity.setDeptId(dto.getDeptId());
            nurseFormEntity.setCtlId(dto.getCtlId());
            nurseFormEntity.setRoleType(dto.getRoleType());
            nurseFormEntity.setApplicableObject(dto.getApplicableObject());
            nurseFormEntity.setModifyUserId(userId);
            nurseFormService.update(nurseFormEntity);
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result queryList(String text, String roleType, String stopFlag) {
        List<Map<String, String>> list = nurseCatalogMapper.queryList(text, roleType, stopFlag);
        return ResultGenerator.genOkResult(list);
    }

    @Override
    public Result changeStatus(String id, String type) {
        if (NurseEnum.NURSE_TYPE_ONE.getIndex().equals(type)) {
            NurseCatalogEntity catalogEntity = this.findById(id);
            if (NurseEnum.STOP_FLAG_ZERO.getIndex().equals(catalogEntity.getStopFlag())) {
                NurseFormEntity entity = new NurseFormEntity();
                entity.setDelFlag(NurseEnum.DEL_FLAG_ZERO.getIndex());
                entity.setStopFlag(NurseEnum.STOP_FLAG_ZERO.getIndex());
                entity.setCtlId(id);
                int count = nurseFormMapper.selectCount(entity);
                if (count > 0) {
                    return ResultGenerator.genFailedResult("当前目录下含有表单，无法停用");
                }
                catalogEntity.setStopFlag(NurseEnum.STOP_FLAG_ONE.getIndex());
            } else {
                catalogEntity.setStopFlag(NurseEnum.STOP_FLAG_ZERO.getIndex());
            }
            this.update(catalogEntity);
        } else {
            NurseFormEntity nurseFormEntity = nurseFormService.findById(id);
            if (NurseEnum.STOP_FLAG_ZERO.getIndex().equals(nurseFormEntity.getStopFlag())) {
                nurseFormEntity.setStopFlag(NurseEnum.STOP_FLAG_ONE.getIndex());
            } else {
                nurseFormEntity.setStopFlag(NurseEnum.STOP_FLAG_ZERO.getIndex());
            }
            nurseFormService.update(nurseFormEntity);
        }
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result addCatalog(NurseFormDTO dto) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        NurseCatalogEntity temp = new NurseCatalogEntity();
        temp.setParentCtlId(dto.getCtlId());
        temp.setDelFlag(NurseEnum.DEL_FLAG_ZERO.getIndex());
        temp.setStopFlag(NurseEnum.STOP_FLAG_ZERO.getIndex());
        int count = nurseCatalogMapper.selectCount(temp);
        NurseCatalogEntity catalogEntity = new NurseCatalogEntity();
        catalogEntity.initAdd();
        BeanUtils.copyProperties(dto, catalogEntity);
        catalogEntity.setCtlId(UUIDUtil.randomString());
        catalogEntity.setParentCtlId(dto.getCtlId());
        catalogEntity.setCreateUserId(userId);
        catalogEntity.setDelFlag(NurseEnum.DEL_FLAG_ZERO.getIndex());
        catalogEntity.setStopFlag(NurseEnum.STOP_FLAG_ZERO.getIndex());
        catalogEntity.setSortId((count + 1) + "");
        try {
            catalogEntity.setPyCode(ChineseCharactersCode.getPinyinCode(dto.getCtlName()).toUpperCase());
            catalogEntity.setWbCode(ChineseCharactersCode.getWBCode(dto.getCtlName()).toUpperCase());
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            logger.error("转拼音出错，字符异常。");
        }
        this.save(catalogEntity);
        return ResultGenerator.genOkResult();
    }

    @Override
    public Result getNurseCatalog() {
        List<ListTreeEntity> nurseCatalog = nurseCatalogMapper.getNurseCatalog();
        List<Tree<ListTreeEntity>> trees = nurseCatalog.stream().map(obj->{
            Tree<ListTreeEntity> tree = new Tree<>();
            tree.setId(obj.getId());
            tree.setParentId(obj.getPid());
            tree.setText(obj.getName());
            return tree;
        }).collect(Collectors.toList());
        Tree<ListTreeEntity> t = TreeCatalogBuildUtil.build(trees);
        return ResultGenerator.genOkResult(t);
    }

    @Override
    public Result getTemplateByCatalogId(String catalogId, String roleType, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Map<String,String>> template = nurseCatalogMapper.getTemplateByCatalogId(catalogId,roleType);
        PageInfo<Map<String,String>> pageInfo = new PageInfo<>(template);
        return ResultGenerator.genOkResult(pageInfo);
    }


}
